import 'package:dict_page_view_plugin/dict_page_view_widget_controller.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:dict_page_view_plugin/dict_page_view_plugin.dart';
import 'package:dict_page_view_plugin/dict_page_view_widget.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';


void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  final _dictPageViewPlugin = DictPageViewPlugin();

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      platformVersion =
          await _dictPageViewPlugin.getPlatformVersion() ?? 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  DictPageViewWidgetController? _controller1;
  DictPageViewWidgetController? _controller2;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app --'),
        ),
        body: Center(
          child: Column(children:[
            Text('Running on: $_platformVersion\n'),
            TextButton(onPressed: () {
              _controller1?.loadUrl(0, 'https://dict.variants.moe.edu.tw/search.jsp?QTP=0&WORD=我');
              _controller2?.loadUrl(0, 'https://www.cnblogs.com');
            }, child: Text('loadBaidu')),
            TextButton(onPressed: () {
              _controller1?.loadTabs([{
                "type": "web",
                "name": "c1",
              },
                {
                  "name": "c2",
                },{
                  "name": "c3",
                },{
                  "name": "c4",
                },{
                  "name": "c5",
                },
              ]);

              _controller2?.loadTabs([{
                "type": "web",
                "name": "c12",
              },
                {
                  "name": "c22",
                },{
                  "name": "c32",
                },{
                  "name": "c42",
                },{
                  "name": "c52",
                },
              ]);
            }, child: Text('reload')),
         Row(children: [
           TextButton(onPressed: () async {
             final imageData = await _controller1!.takePhoto(0);
             if (imageData != null) {
               final result = await ImageGallerySaver.saveImage(imageData);
             }

           }, child: Text("photo")),
           TextButton(onPressed: () async {
             _controller1!.changeTab(1);
             _controller2?.changeTab(2);
           }, child: Text("change tab")),
         ],),

            Expanded(child:  DictPageViewWidget(onDictPageViewCreated: (DictPageViewWidgetController controller) {
              _controller1 = controller;
              _controller1?.setMethodHandler((method, param) async {
                print("...controll1 ${method} ${param}");
                if (method == 'shouldInterceptRequest') {
                  if ((param['url'] as String).endsWith(".png")) {
                    var buf = await rootBundle.load('assets/img/logo.png');
                    return buf.buffer.asUint8List();
                  }
                } else if (method == "shareImage") {
                 // Share.(Uri.parse(param as String));
                }
                return null;
              });
            },)),
            TextButton(onPressed: () {
              _controller2?.changeTab(1);
              _controller1?.changeTab(1);
            }, child: Text('page2')),
            Expanded(child:  DictPageViewWidget(onDictPageViewCreated: (DictPageViewWidgetController controller) {
              _controller2 = controller;
              _controller2?.setMethodHandler((method, param) async {
                print("...controll2 ${method} ${param}");
                if (method == 'shouldOverrideUrlLoading') {
                  if (param['url'] == 'https://www.cnblogs.com/boycelee/p/18355942') {
                    return true;
                  }
                }
                return null;
              });
            },))
          ]),
        ),
      ),
    );
  }
}
